# coding; utf-8

import os
from collections import namedtuple

import handler.jsonp as jsonHandler

DEFUALT_ENTITY_NAME = '_entity'
class Entity(object):
    def __init__(self, class_name, **kwargs):
        super(Entity, self).__init__()
        _columns = kwargs.keys()
        columns = list(set(_columns))
        entity = namedtuple(class_name, columns)
        self._entity = entity(**kwargs)

    def __getattribute__(self, key):
        entity = super(Entity, self).__getattribute__(DEFUALT_ENTITY_NAME)
        try:
            return super(Entity, self).__getattribute__(key)
        except:
            try:
                return getattr(entity, key)
            except:
                return None

    def __setattr__(self, key, value):
        if key == DEFUALT_ENTITY_NAME:
            super(Entity, self).__setattr__(DEFUALT_ENTITY_NAME, value)
            return
        entity = super(Entity, self).__getattribute__(DEFUALT_ENTITY_NAME)
        try:  # setattr(entity, key, value)
            entity.__setattr__(key, value)
        except:
            super(Entity, self).__setattr__(key, value)

    def mapper(self, classes):
        instance = classes()
        items = vars(self).items()
        if len(items) == 1:
            item = items[0][1]
            items = vars(item).items()
        attributes = dir(instance)
        for (key, value) in items:
            if attributes.count(key) == 0:
                continue
            instance._data[key] = value
        return instance

    def __str__(self):
        items = vars(self).items()
        if len(items) == 1:
            item = items[0][1]
            items = vars(item).items()
        string = ''
        for (key, value) in items:
            if key == DEFUALT_ENTITY_NAME:
                continue
            string += u'{0}={1}{2}'.format(key, value, os.linesep)
        return string

    def json(self):
        return jsonHandler.to_json(self)
